/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.outpost.util.ipr;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sven Schulz
 */
public class MacAddress {

	public static Map<MacAddress, InterfaceAddress> getAddresses()
			throws SocketException {
		Map<MacAddress, InterfaceAddress> addresses = new HashMap<MacAddress, InterfaceAddress>();
		for (Enumeration<NetworkInterface> e = NetworkInterface
				.getNetworkInterfaces(); e.hasMoreElements();) {
			NetworkInterface intf = e.nextElement();
			if (intf.isLoopback() || !intf.isUp())
				continue;
			byte[] mac = intf.getHardwareAddress();
			if (mac == null)
				continue;
			for (InterfaceAddress intfAddr : intf.getInterfaceAddresses()) {
				InetAddress addr = intfAddr.getAddress();
				if (addr instanceof Inet6Address)
					continue;
				addresses.put(new MacAddress(mac), intfAddr);
				break;
			}
		}
		return addresses;
	}

	private byte[] raw;

	public MacAddress(String s) {
		s = s.contains("-") ? s.replaceAll("-", "") : s;
		s = s.toUpperCase();
		raw = new byte[6];
		for (int i = 0; i < 6; i++) {
			raw[i] = (byte) Integer.parseInt(s.substring(2 * i, 2 * (i + 1)),
					16);
		}
	}

	public MacAddress(byte[] raw) {
		this.raw = raw;
	}

	public byte[] getRaw() {
		return raw;
	}

	@Override
	public int hashCode() {
		return Arrays.hashCode(raw);
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == null || !(obj instanceof MacAddress)) {
			return false;
		}
		MacAddress other = (MacAddress) obj;
		return Arrays.equals(raw, other.raw);
	}

	@Override
	public String toString() {
		StringBuilder b = new StringBuilder();
		for (byte r : raw) {
			if (b.length() != 0)
				b.append('-');
			String h = Integer.toHexString(r);
			b.append((h.length() == 1 ? "0" : "")
					+ (h.length() <= 2 ? h : h.substring(h.length() - 2)));
		}
		return b.toString().toUpperCase();
	}

}